package com.hmall.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.utils.CollUtils;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.domain.vo.PageVO;
import com.hmall.search.mapper.ItemMapper;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SearchServiceImpl
 * Package:
 * Description
 *
 * @Author xw
 * @Create 2023/12/22 17:49
 */
@Slf4j
@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    private ItemClient itemClient;

    private RestHighLevelClient client;

    private final String INDEX_NAME = "items";

    {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.217.67:9200")
        ));
    }

    // 自动补
    @Override
    public List<String> getSuggestion(String prefix) {

        System.out.println("自动补全：" + prefix);

        try {
            // 1.创建Request
            SearchRequest request = new SearchRequest(INDEX_NAME);

            // 2.准备DSL
            request.source().fetchSource(
                    new String[0], null
            );


            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("My_SUGGESTION",
                            SuggestBuilders.completionSuggestion("name")
                                    .size(10)
                                    .skipDuplicates(true)
                                    .prefix(prefix)
                    )

            );

            // 发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);


            // 解析结果
            CompletionSuggestion suggester = response.getSuggest().getSuggestion("My_SUGGESTION");

            // 4.1.获取suggestion
            List<CompletionSuggestion.Entry.Option> options = suggester.getOptions();

            // 4.2.获取options
            List<String> list = new ArrayList<>(options.size());

            // 4.3.循环遍历，获取text
            for (CompletionSuggestion.Entry.Option option : suggester.getOptions()) {
                list.add(option.getText().string());
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 过滤项聚合功能
    @Override
    public Map<String, List<String>> searchPost(ItemPageQuery query) {
        // 创建返回结果的Map
        Map<String, List<String>> resultMap = new HashMap<>();
        try {
            // 创建SearchRequest对象，指定索引名称
            SearchRequest request = new SearchRequest(INDEX_NAME);
            // 准备DSL语句，设置返回结果为0，因为我们只需要聚合结果，不需要具体的文档数据
            request.source().size(0);
            // 构建基本查询条件
            buildBasicQuery(query, request);
            // 添加品牌聚合
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
            // 添加类别聚合
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
            // 发送请求，获取响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 获取聚合结果
            Aggregations aggregations = response.getAggregations();

            // 获取品牌聚合结果，并添加到结果Map中
            List<String> brandList = getAggregationResult(aggregations, "brandAgg");
            resultMap.put("brand", brandList);
            // 获取类别聚合结果，并添加到结果Map中
            List<String> categoryList = getAggregationResult(aggregations, "categoryAgg");
            resultMap.put("category", categoryList);

            return resultMap;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 解析聚合结果方法，根据聚合名称获取聚合结果列表
    private List<String> getAggregationResult(Aggregations aggregations, String aggName) {
        List<String> resultList = new ArrayList<>();
        Terms agg = aggregations.get(aggName);
        for (Terms.Bucket bucket : agg.getBuckets()) {
            String key = bucket.getKeyAsString(); // 获取聚合结果的key（品牌或类别名称）
            resultList.add(key);
        }
        return resultList;
    }


    // 实现基本搜索功能
    @Override
    public PageVO<ItemDoc> search(ItemPageQuery query) {
        // 1.创建Request
        SearchRequest request = new SearchRequest("items");
        // 多条件查询
        buildBasicQuery(query, request);
        // 分页
        Integer pageNo = query.getPage();      // 页码
        Integer pageSize = query.getSize();  // 每业大小

        // 排序
        String sortBy = query.getSortBy(); // default sold price
        Boolean isAsc = query.getIsAsc();  // 排序规则

        // 不能与空，并且不等于 default
        if (!sortBy.isEmpty() && !"default".equals(sortBy)) {
            SortOrder sortOrder = isAsc ? SortOrder.DESC : SortOrder.ASC;
            request.source().sort(sortBy, sortOrder);
        }

        // 分页参数
        request.source().from((pageNo - 1) * pageSize).size(pageSize);
        SearchResponse response = null;
        try {
            // 3.发送请求
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("SearchServiceImpl 类 PageVO 方法，发送请求出现异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        // 4.解析响应
        return handleResponse(response, pageNo);
    }


    //  修改商品状态
    @Override
    public void saveItemById(Long itemId) {
        // 根据id查询商品
        Item item = itemClient.queryItemById(itemId);
        if (item.getId() == null) {
            return;
        }

        try {
            // 1.准备Request对象
            IndexRequest request = new IndexRequest(INDEX_NAME).id(itemId.toString());
            // 2.准备请求参数
            request.source(JSONUtil.toJsonStr(BeanUtil.copyProperties(item, Item.class)), XContentType.JSON);

            System.out.println("---->\n"+item);

            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("更新商品失败，商品id：" + itemId, e);
        }
    }

    @Override
    public void deleteItemById(Long itemId) {
        try {
            // 1.准备Request对象
            DeleteRequest request = new DeleteRequest(INDEX_NAME, itemId.toString());
            // 3.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("删除商品失败，商品id：" + itemId, e);
        }
    }


    // 多条件查询
    private void buildBasicQuery(ItemPageQuery query, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        request.source().query(boolQueryBuilder);
        // 构建关键字查询条件，如果关键字为空，则使用match_all查询，否则使用match查询匹配商品名称
        if (StringUtils.isEmpty(query.getKey())) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        // 构建分类过滤条件，如果分类不为空，则使用term查询过滤分类字段
        if (StringUtils.isNotEmpty(query.getCategory())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", query.getCategory()));
        }
        // 构建品牌过滤条件，如果品牌不为空，则使用term查询过滤品牌字段
        if (StringUtils.isNotEmpty(query.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", query.getBrand()));
        }
        // 构建价格过滤条件，如果最小价格和最大价格都不为空，则使用range查询过滤价格字段
        if (query.getMinPrice() != null && query.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
        }
    }

    // 解析响应 em
    private PageVO<ItemDoc> handleResponse(SearchResponse response, Integer pageNo) {
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        Long total = searchHits.getTotalHits().value;

        // 2.遍历结果数组
        SearchHit[] hits = searchHits.getHits();

        List<ItemDoc> list = new ArrayList<>();

        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化并打印
            ItemDoc item = JSONUtil.toBean(source, ItemDoc.class);
            list.add(item);
        }
        // 封装返回
        return PageVO.of(total, Long.getLong(pageNo.toString()), list);


    }

}
